package com.lyz.dataStructure.面试算法题.GrowingIO;

/**
 *@Author:759057893@qq.com Lyz
 *@Date: 2019/9/2 13:51
 *@Description:
 **/

/*
两条线程实现交替打印奇偶数
 */
public class ThreadExchange {

    private static Object lock = new Object();

    private static int i = 1;

    public static void main(String[] args) {
        Thread t1 = new Thread(new Thread1());
        Thread t2 = new Thread(new Thread2());
        t1.start();
        t2.start();
    }

    static class  Thread1 implements Runnable{
        @Override
        public void run() {
            while (i<=100){
                synchronized (lock){
                    if (i%2==1){
                        System.out.println("Thread1  " + i++);
                    }else {
                        lock.notifyAll();
                        try {
                            lock.wait(1000);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        }
    }
    static class  Thread2 implements Runnable{
        @Override
        public void run() {
            while (i<=100){
                synchronized (lock){
                    if (i%2==0){
                        System.out.println("Thread2  " + i++);
                    }else {
                        lock.notifyAll();
                        try {
                            lock.wait(1000);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        }
    }
}

